package com.yuyou.fn.interceptor;

import com.github.wens.mybatisplus.toolkit.IdWorker;
import com.yuyou.fn.common.util.Logs;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.platform.vo.AccessTokenVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by wens on 16-12-14.
 */
public class LogInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestId = Utils.to62(IdWorker.getId());
        request.setAttribute("requestId" , requestId );
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String requestId = (String) request.getAttribute("requestId");
        AccessTokenVo accessToken = (AccessTokenVo)request.getAttribute("accessToken");
        StringBuilder out = new StringBuilder(500 );
        out.append("accessLog:[");
        out.append("requestId=").append(requestId);
        out.append(",uri=").append(request.getRequestURI());
        out.append(",principalId=").append(accessToken == null ? StringUtils.EMPTY : accessToken.getUserId() );
        out.append(",principalName=").append(accessToken == null ? StringUtils.EMPTY : accessToken.getName() );
        out.append(",params={").append(requestParams(request)).append("}");
        out.append(",executeResult=").append(ex == null ? "success" : "fail").append("]");
        Logs.logAction(out.toString());
    }

    private String requestParams(HttpServletRequest request) {
        Map parameterMap = request.getParameterMap();
        List<String>  params = new ArrayList<>(parameterMap.size());
        for(Object key  : parameterMap.keySet() ){
            StringBuilder sb  = new StringBuilder(10) ;
            Object o = parameterMap.get(key);
            sb.append(key).append("=").append(o.getClass().isArray() ? Arrays.toString((Object[]) o) : o );
            params.add(sb.toString());
        }
        return StringUtils.join(params,",") ;
    }
}
